#include "ImageManagementPlugin.h"
#include "ImagePreviewWidget.h"
#include "CameraPluginInterface.h"
#include "ImageOperation.h"
#include <functional>
#include <QImage>
#include <QMetaType>
#include <QAction>

//图形预处理菜单名称
#define IMAGE_PREPROCESSING_MENU_NAME "图形预处理(P)"
//图形预处理配置名称
#define IMAGE_PREPROCESSING_SETTINGS_NAME "ImagePreprocessingConfig"

ImageManagementPlugin::ImageManagementPlugin(QObject *parent) : CameraPluginInterface(parent),
    m_pPreviewWidget(nullptr), m_imageCacheManager(nullptr), m_undoRedoManager(nullptr),m_CameraUpdateImageCallback(nullptr),
    m_ImagePreprocessingSettings(nullptr)
{
    connect(this,&ImageManagementPlugin::updateCameraImage,this,[this](const QImage& image)
    {
        if(this->m_CameraUpdateImageCallback)
        {
            m_CameraUpdateImageCallback(nullptr,image);
        }
    },Qt::BlockingQueuedConnection);
}

ImageManagementPlugin::~ImageManagementPlugin()
{
    delete m_imageCacheManager;
    delete m_undoRedoManager;
}

void ImageManagementPlugin::initialize() {
//    qRegisterMetaType<std::function<void(const QString&, const QImage&, int)>>("ImageCallback");
    // 创建图像缓存管理器
    if (!m_imageCacheManager) {
        m_imageCacheManager = new ImageCacheManager(this);
    }

    // 创建撤销/重做管理器
    if (!m_undoRedoManager) {
        m_undoRedoManager = new UndoRedoManager(this);
        // 设置最大历史记录数量
        m_undoRedoManager->setMaxHistorySize(50);
    }

    if (!m_pPreviewWidget) {
        m_pPreviewWidget = new ImagePreviewWidget;
        // 设置缓存管理器（使用ImageManagementPlugin中的实例）
        m_pPreviewWidget->setCacheManager(m_imageCacheManager);
        // 初始化预览组件（可扩展：加载默认图像、设置显示参数等）
        // 连接ImagePreviewWidget的注册请求信号
        connect(m_pPreviewWidget, &ImagePreviewWidget::requestRegisterImageDisplay, this, &ImageManagementPlugin::onRequestRegisterImageDisplay);
        // 连接预览项点击信号
        connect(m_pPreviewWidget, &ImagePreviewWidget::displayImageRequested, this, &ImageManagementPlugin::onDisplayImageRequested);
        // 连接切换图形显示窗口信号
        connect(m_pPreviewWidget, &ImagePreviewWidget::switchToPreviewItem, this, &ImageManagementPlugin::onSwitchToPreviewItem);
        connect(this, &ImageManagementPlugin::switchToGraphicsDisplayWidget, this, &ImageManagementPlugin::onSwitchToGraphicsDisplayWidget);
        // 连接预览项删除信号，以便同步关闭显示界面
        connect(m_pPreviewWidget, &ImagePreviewWidget::PreviewItemDelete, this, &ImageManagementPlugin::onImageRemovedFromCache);
        // 连接撤销/重做请求信号
        connect(m_pPreviewWidget, &ImagePreviewWidget::undoRequested, this, &ImageManagementPlugin::onUndoRequested);
        connect(m_pPreviewWidget, &ImagePreviewWidget::redoRequested, this, &ImageManagementPlugin::onRedoRequested);
    }
    emit registerWidgetToDock(DockWidgetType::ImagePreview,m_pPreviewWidget);
}

void ImageManagementPlugin::onRequestRegisterImageDisplay(const QString &imageGuid)
{
    QImage displayImage = m_pPreviewWidget->getImage(imageGuid);

    if (!displayImage.isNull()) {
        // 只发送消息给图形显示插件，让它主动来调用图像管理插件的接口
        emit pluginMessageSent(IMAGE_MANAGEMENT_PLUGIN_NAME, QString("%1:%2:%3").arg(CMD_REGISTER_IMAGE_DISPLAY).arg(imageGuid).arg(imageGuid.left(8)), GRAPHICS_DISPLAY_PLUGIN_NAME);
        onDisplayImageRequested(imageGuid);

        // 发送消息通知其他可能关注当前选中图像的插件
        emit pluginMessageSent(IMAGE_MANAGEMENT_PLUGIN_NAME, QString(CMD_IMAGE_SELECTED ":%1").arg(imageGuid));
    }
}

void ImageManagementPlugin::onDisplayImageRequested(const QString &imageGuid)
{
    // 根据是否有处理后的图像来决定发送哪个更新指令
    if (m_imageCacheManager && m_imageCacheManager->containsImage(imageGuid)) {
        QImage processedImage = m_imageCacheManager->getProcessedImage(imageGuid);
        if (!processedImage.isNull()) {
            // 如果有处理后的图像，发送更新处理后图像指令
            emit pluginMessageSent(IMAGE_MANAGEMENT_PLUGIN_NAME, QString(CMD_UPDATE_PROCESSED_IMAGE ":%1").arg(imageGuid), GRAPHICS_DISPLAY_PLUGIN_NAME);
        } else {
            // 如果没有处理后的图像，发送更新原始图像指令
            emit pluginMessageSent(IMAGE_MANAGEMENT_PLUGIN_NAME, QString(CMD_UPDATE_IMAGE_DISPLAY ":%1").arg(imageGuid), GRAPHICS_DISPLAY_PLUGIN_NAME);
        }
    }
}

void ImageManagementPlugin::onSwitchToPreviewItem(const QString &imageGuid)
{
    onRequestRegisterImageDisplay(imageGuid);
    // 然后向主窗口发送switchToGraphicsDisplayWidget信号，触发主窗口切换到对应的图形显示窗口
    emit switchToGraphicsDisplayWidget(imageGuid);
}

// 保留updateImageDisplay函数但内部调用onDisplayImageRequested以保持兼容性
void ImageManagementPlugin::updateImageDisplay(const QString &imageGuid)
{
    onDisplayImageRequested(imageGuid);
}

void ImageManagementPlugin::onImageRemovedFromCache(const QString &imageGuid)
{
    // 当图像预览项被删除时，发送消息让图形显示插件主动来调用图像管理插件的接口

    // 添加额外的参数验证，防止传递无效的GUID
    if (imageGuid.isEmpty()) {
        qWarning() << "尝试注销图像显示界面，但GUID为空";
        return;
    }
    //发送给设备管理看是否需要关闭相机连接
    emit pluginMessageSent(IMAGE_MANAGEMENT_PLUGIN_NAME, QString(CMD_UNREGISTER_IMAGE_DISPLAY ":%1").arg(imageGuid), DEVICE_MANAGEMENT_PLUGIN_NAME);
    // 发送消息给图形显示插件
    emit pluginMessageSent(IMAGE_MANAGEMENT_PLUGIN_NAME, QString(CMD_UNREGISTER_IMAGE_DISPLAY ":%1").arg(imageGuid), GRAPHICS_DISPLAY_PLUGIN_NAME);
}

void ImageManagementPlugin::onUndoRequested(const QString &imageGuid)
{
    // 处理撤销请求
    if (!imageGuid.isEmpty() && m_undoRedoManager && m_undoRedoManager->canUndo(imageGuid))
    {
        qDebug() << "执行撤销操作，图像GUID：" << imageGuid;
        // 调用撤销/重做管理器执行撤销操作
        m_undoRedoManager->undo(imageGuid);
        // 通知图形显示插件更新图像显示
        onDisplayImageRequested(imageGuid);
    }
    else
    {
        qDebug() << "无法执行撤销操作，图像GUID：" << imageGuid;
    }
}

void ImageManagementPlugin::onRedoRequested(const QString &imageGuid)
{
    // 处理重做请求
    if (!imageGuid.isEmpty() && m_undoRedoManager && m_undoRedoManager->canRedo(imageGuid))
    {
        qDebug() << "执行重做操作，图像GUID：" << imageGuid;
        // 调用撤销/重做管理器执行重做操作
        m_undoRedoManager->redo(imageGuid);
        // 通知图形显示插件更新图像显示
        onDisplayImageRequested(imageGuid);
    }
    else
    {
        qDebug() << "无法执行重做操作，图像GUID：" << imageGuid;
    }
}

void ImageManagementPlugin::onImagePreprocessingSetting(int result)
{
    if(result!=QDialog::Accepted)
    {
        return;
    }
    QVariant ret;
    QVariantList args;
    args << IMAGE_PREPROCESSING_SETTINGS_NAME;
    args << m_ImagePreprocessingSettings->collectParameters();
    requestPluginFunctionCall(DEVELOPER_MODE_PLUGIN_NAME,"setConfigParams",args,ret);
}

void ImageManagementPlugin::onSwitchToGraphicsDisplayWidget(const QString &graphicsGuid)
{
    qDebug()<<sender()<<graphicsGuid;
    // 处理从主框架发下来的切换图形显示窗口信号
    // 首先检查图像是否存在于缓存中
    if (m_pPreviewWidget->getCacheManager()->containsImage(graphicsGuid)) {
        // 更新当前选中的图像（使用新的setSelectedImageGuid方法避免信号循环）
        m_pPreviewWidget->setSelectedImageGuid(graphicsGuid);
    }
}

QVariant ImageManagementPlugin::getCurrentSelectedImageGuid()
{
    if (!m_pPreviewWidget) {
        return QVariant();
    }

    // 直接返回ImagePreviewWidget中记录的当前选中图像GUID
    return m_pPreviewWidget->getCurrentSelectedGuid();
}


QString ImageManagementPlugin::pluginName() const {
    return IMAGE_MANAGEMENT_PLUGIN_NAME;
}

QString ImageManagementPlugin::description() const {
    return "提供图像加载、预览及保存功能，支持与其他插件协同处理图像数据";
}

void ImageManagementPlugin::onPluginMessage(const QString& sender, const QString& message) {

    Q_UNUSED(sender)
    // 处理图像处理请求消息
    if (message.startsWith(CMD_PROCESS_IMAGE ":")) {
        QString algorithmName = message.mid(strlen(CMD_PROCESS_IMAGE) + 1); // 提取算法名称
        qDebug() << "Received image processing request for algorithm: " << algorithmName;

        // 获取当前选中图像的GUID
        QVariant selectedGuid = getCurrentSelectedImageGuid();
        if (selectedGuid.isValid())
        {
            QString imageGuid = selectedGuid.toString();

            // 检查图像是否存在
            if (!(m_imageCacheManager && m_imageCacheManager->containsImage(imageGuid)))
            {
                qWarning() << "Image not found in cache: " << imageGuid;
            }
            // 只发送消息给图像处理算法管理插件，让它主动来调用图像管理插件的接口
            emit pluginMessageSent(IMAGE_MANAGEMENT_PLUGIN_NAME, QString(CMD_IMAGE_READY_FOR_PROCESSING ":%1:%2").arg(imageGuid).arg(algorithmName), IMAGE_PROCESSING_ALGORITHM_MANAGER_PLUGIN_NAME);
        }
        else
        {
            qWarning() << "No selected image to process";
        }
    }
    //q
    else if (message.startsWith(QString(CMD_CAMERA_CONNECTED ":"))) {
        QStringList parts = message.split(":");
        if (parts.size() >= 2) {
            const QString deviceId = parts[1];
            if (!deviceId.isEmpty()) {
                // 注册图像显示并切换到对应窗口
                onRequestRegisterImageDisplay(deviceId);
                emit switchToGraphicsDisplayWidget(deviceId);

                // 通过反射让SDK管理插件注册图像采集回调
                QVariant ret;
                QVariantList args;
                args << QVariant(deviceId)
                     << "相机实时图像";
                bool ok=emit requestPluginFunctionCall(GRAPHICS_DISPLAY_PLUGIN_NAME,"registerImageDisplayWidget",args,ret);
                if (!ok||!ret.toBool()) {
                    qWarning() << "Failed to register image display for device" << deviceId;
                    return;
                }
                m_imageCacheManager->addImageToCache(deviceId,QImage());
                args.removeAt(1);
                ok=emit requestPluginFunctionCall(GRAPHICS_DISPLAY_PLUGIN_NAME,"getUpdateDisplayImageWidget",args,ret);
                if (!ok||!ret.canConvert<QWidget*>()) {
                    qWarning() << "Failed to get Update Display Image Widget" << deviceId;
                    return;
                }
                QWidget* pWidget=ret.value<QWidget*>();
                ok=emit requestPluginFunctionCall(GRAPHICS_DISPLAY_PLUGIN_NAME,"getUpdateDisplayImageCallback",args,ret);
                if(!ok||!ret.canConvert<quintptr>())
                {
                    qWarning() << "Failed to get Update Display Image Callback" << deviceId;
                    return;
                }
                void (*updateCameraImage)(QObject* , const QImage&)=
                        reinterpret_cast<void (*)(QObject*, const QImage&)>(ret.value<qintptr>());
                m_CameraUpdateImageCallback=[pWidget,updateCameraImage](const QWidget *, const QImage &image)
                {
                    updateCameraImage(pWidget,image);
                };
                args<< QVariant::fromValue((QObject*)this)<< reinterpret_cast<qintptr>(handleCapturedImage);
                ok =emit requestPluginFunctionCall(DEVICE_MANAGEMENT_PLUGIN_NAME, "setImageCaptureCallback", args, ret);
                if (!ok||!ret.toBool()) {
                    qWarning() << "Failed to register image capture callback for device" << deviceId;
                }
            }
        }
    }
    // 处理测量请求消息
    else if (message.startsWith(CMD_MEASUREMENT_REQUEST ":")) {
        // 消息格式: "MEASUREMENT_REQUEST:algorithmName:measurementType"
        QStringList parts = message.split(":");
        if (parts.size() >= 3) {
            QString algorithmName = parts[1];
            QString measurementType = parts[2];

            // 获取当前选中图像的GUID
            QVariant selectedGuid = getCurrentSelectedImageGuid();
            if (selectedGuid.isValid()) {
                QString imageId = selectedGuid.toString();
                // 检查图像是否存在
                if (m_imageCacheManager && m_imageCacheManager->containsImage(imageId)) {
                    // 向测量管理插件发送测量准备完成消息
                    QString responseMessage = QString(CMD_MEASUREMENT_READY ":%1:%2:%3").arg(algorithmName).arg(imageId).arg(measurementType);
                    emit pluginMessageSent(IMAGE_MANAGEMENT_PLUGIN_NAME, responseMessage, MEASUREMENT_MANAGEMENT_PLUGIN_NAME);
                } else {
                    qWarning() << "图像不存在于缓存中:" << imageId;
                }
            } else {
                qWarning() << "没有选中的图像用于测量";
            }
        }
    }
    //处理相机断开消息
    else if (message.startsWith(QString(CMD_CAMERA_DISCONNECTED ":"))) {
        QStringList parts = message.split(":");
        if (parts.size() >= 2) {
            const QString deviceId = parts[1];
            if (!deviceId.isEmpty()) {
                // 注销图像显示（并从缓存中移除）
                onImageRemovedFromCache(deviceId);

                // 通过反射让SDK管理插件注销图像采集回调
                QVariant ret;
                QVariantList args;
                args << QVariant(deviceId);
                bool ok= requestPluginFunctionCall(GRAPHICS_DISPLAY_PLUGIN_NAME,"unregisterImageDisplayWidget",args,ret);
                if (!ok||ret.toBool()) {
                    qWarning() << "Failed to unregister image display for device" << deviceId;
                }
            }
        }
    }
    else if(message.startsWith(QString(CMD_FRAMEWORK_INITIALIZED)))
    {
        if(m_ImagePreprocessingSettings)
        {
            return;
        }
        m_ImagePreprocessingSettings=new ImagePreprocessingSettings(m_pPreviewWidget);
        QVariant ret;
        QVariantList args;
        args << IMAGE_PREPROCESSING_MENU_NAME<<QVariant::fromValue(m_ImagePreprocessingSettings);
        bool ok= emit requestPluginFunctionCall(DEVELOPER_MODE_PLUGIN_NAME,"registerPresetParamMenuItem",args,ret);
        if (!ok||!ret.toBool())
        {
            return;
        }
        ret.clear();
        args.clear();
        args << IMAGE_PREPROCESSING_SETTINGS_NAME;
        ok= emit requestPluginFunctionCall(DEVELOPER_MODE_PLUGIN_NAME,"getConfigParams",args,ret);
        if (!ok||!ret.canConvert<QMap<QString, QVariant>>())
        {
            return;
        }
        m_ImagePreprocessingSettings->setParameters(ret.toMap());
        connect(m_ImagePreprocessingSettings,&ImagePreprocessingSettings::finished,this,&ImageManagementPlugin::onImagePreprocessingSetting);
    }
}

QVariant ImageManagementPlugin::getImageLengthRatio(const QVariant &imageGuid) {
    if (!m_imageCacheManager || !imageGuid.isValid()) {
        return 1.0;
    }

    QString guid = imageGuid.toString();
    return m_imageCacheManager->getLengthRatio(guid);
}

QVariant ImageManagementPlugin::setImageLengthRatio(const QVariant &imageGuid, const QVariant &ratio) {
    if (!m_imageCacheManager || !m_undoRedoManager || !imageGuid.isValid() || !ratio.isValid()) {
        return false;
    }

    QString guid = imageGuid.toString();
    double ratioValue = ratio.toDouble();

    // 获取当前的比例值用于撤销操作
    double oldRatio = m_imageCacheManager->getLengthRatio(guid);

    // 创建撤销函数
    auto undoFunc = [this, guid, oldRatio](const QVariant&) {
        if (m_imageCacheManager->containsImage(guid)) {
            m_imageCacheManager->setLengthRatio(guid, oldRatio);
            return true;
        }
        return false;
    };

    // 创建重做函数
    auto redoFunc = [this, guid, ratioValue](const QVariant&) {
        if (m_imageCacheManager->containsImage(guid)) {
            m_imageCacheManager->setLengthRatio(guid, ratioValue);
            return true;
        }
        return false;
    };

    // 创建操作信息结构体
    OperationInfo info;
    info.imageGuid = guid;
    info.type = ImageOperationType::AxisParamsChange;
    info.previousValue = QVariant(oldRatio);
    info.newValue = QVariant(ratioValue);
    info.undoFunc = undoFunc;
    info.redoFunc = redoFunc;
    info.description = tr("修改长度比例");

    // 添加到撤销/重做管理器
    m_undoRedoManager->addOperation(info);

    m_imageCacheManager->setLengthRatio(guid, ratioValue);
    return true;
}

QVariant ImageManagementPlugin::getImageTimeRatio(const QVariant &imageGuid) {
    if (!m_imageCacheManager || !imageGuid.isValid()) {
        return 1.0;
    }

    QString guid = imageGuid.toString();
    return m_imageCacheManager->getTimeRatio(guid);
}

QVariant ImageManagementPlugin::setImageTimeRatio(const QVariant &imageGuid, const QVariant &ratio) {
    if (!m_imageCacheManager || !m_undoRedoManager || !imageGuid.isValid() || !ratio.isValid()) {
        return false;
    }

    QString guid = imageGuid.toString();
    double ratioValue = ratio.toDouble();

    // 获取当前的比例值用于撤销操作
    double oldRatio = m_imageCacheManager->getTimeRatio(guid);

    // 创建撤销函数
    auto undoFunc = [this, guid, oldRatio](const QVariant&) {
        if (m_imageCacheManager->containsImage(guid)) {
            m_imageCacheManager->setTimeRatio(guid, oldRatio);
            return true;
        }
        return false;
    };

    // 创建重做函数
    auto redoFunc = [this, guid, ratioValue](const QVariant&) {
        if (m_imageCacheManager->containsImage(guid)) {
            m_imageCacheManager->setTimeRatio(guid, ratioValue);
            return true;
        }
        return false;
    };

    // 创建操作信息结构体
    OperationInfo info;
    info.imageGuid = guid;
    info.type = ImageOperationType::AxisParamsChange;
    info.previousValue = QVariant(oldRatio);
    info.newValue = QVariant(ratioValue);
    info.undoFunc = undoFunc;
    info.redoFunc = redoFunc;
    info.description = tr("修改时间比例");

    // 添加到撤销/重做管理器
    m_undoRedoManager->addOperation(info);

    m_imageCacheManager->setTimeRatio(guid, ratioValue);
    return true;
}

QVariant ImageManagementPlugin::getImageWavelengthRatio(const QVariant &imageGuid) {
    if (!m_imageCacheManager || !imageGuid.isValid()) {
        return 1.0;
    }

    QString guid = imageGuid.toString();
    return m_imageCacheManager->getWavelengthRatio(guid);
}

QVariant ImageManagementPlugin::setImageWavelengthRatio(const QVariant &imageGuid, const QVariant &ratio) {
    if (!m_imageCacheManager || !m_undoRedoManager || !imageGuid.isValid() || !ratio.isValid()) {
        return false;
    }

    QString guid = imageGuid.toString();
    double ratioValue = ratio.toDouble();

    // 获取当前的比例值用于撤销操作
    double oldRatio = m_imageCacheManager->getWavelengthRatio(guid);

    // 创建撤销函数
    auto undoFunc = [this, guid, oldRatio](const QVariant&) {
        if (m_imageCacheManager->containsImage(guid)) {
            m_imageCacheManager->setWavelengthRatio(guid, oldRatio);
            return true;
        }
        return false;
    };

    // 创建重做函数
    auto redoFunc = [this, guid, ratioValue](const QVariant&) {
        if (m_imageCacheManager->containsImage(guid)) {
            m_imageCacheManager->setWavelengthRatio(guid, ratioValue);
            return true;
        }
        return false;
    };

    // 创建操作信息结构体
    OperationInfo info;
    info.imageGuid = guid;
    info.type = ImageOperationType::AxisParamsChange;
    info.previousValue = QVariant(oldRatio);
    info.newValue = QVariant(ratioValue);
    info.undoFunc = undoFunc;
    info.redoFunc = redoFunc;
    info.description = tr("修改波长比例");

    // 添加到撤销/重做管理器
    m_undoRedoManager->addOperation(info);

    m_imageCacheManager->setWavelengthRatio(guid, ratioValue);
    return true;
}

QVariant ImageManagementPlugin::getImageLengthUnit(const QVariant &imageGuid) {
    if (!m_imageCacheManager || !imageGuid.isValid()) {
        return "mm";
    }

    QString guid = imageGuid.toString();
    // 从缓存管理器获取单位信息
    return m_imageCacheManager->getLengthUnit(guid);
}

QVariant ImageManagementPlugin::getImageTimeUnit(const QVariant &imageGuid) {
    if (!m_imageCacheManager || !imageGuid.isValid()) {
        return "us";
    }

    QString guid = imageGuid.toString();
    // 从缓存管理器获取单位信息
    return m_imageCacheManager->getTimeUnit(guid);
}

QVariant ImageManagementPlugin::getImageWavelengthUnit(const QVariant &imageGuid) {
    if (!m_imageCacheManager || !imageGuid.isValid()) {
        return "nm";
    }

    QString guid = imageGuid.toString();
    // 从缓存管理器获取单位信息
    return m_imageCacheManager->getWavelengthUnit(guid);
}

QVariant ImageManagementPlugin::setImageLengthUnit(const QVariant &imageGuid, const QVariant &unit) {
    if (!m_imageCacheManager || !imageGuid.isValid() || !unit.isValid()) {
        return false;
    }

    QString guid = imageGuid.toString();
    QString unitString = unit.toString();
    // 保存单位信息到缓存管理器
    m_imageCacheManager->setLengthUnit(guid, unitString);
    return true;
}

QVariant ImageManagementPlugin::setImageTimeUnit(const QVariant &imageGuid, const QVariant &unit) {
    if (!m_imageCacheManager || !imageGuid.isValid() || !unit.isValid()) {
        return false;
    }

    QString guid = imageGuid.toString();
    QString unitString = unit.toString();
    // 保存单位信息到缓存管理器
    m_imageCacheManager->setTimeUnit(guid, unitString);
    return true;
}

QVariant ImageManagementPlugin::setImageWavelengthUnit(const QVariant &imageGuid, const QVariant &unit) {
    if (!m_imageCacheManager || !imageGuid.isValid() || !unit.isValid()) {
        return false;
    }

    QString guid = imageGuid.toString();
    QString unitString = unit.toString();
    // 保存单位信息到缓存管理器
    m_imageCacheManager->setWavelengthUnit(guid, unitString);
    return true;
}

QVariant ImageManagementPlugin::setImageConversionInfo(const QVariant &imageGuid, const QVariant &lengthRatio, const QVariant &timeRatio, const QVariant &wavelengthRatio, const QVariant &lengthUnit, const QVariant &timeUnit, const QVariant &wavelengthUnit, const QVariant &xAxisUnit, const QVariant &yAxisUnit) {
    if (!m_imageCacheManager || !m_undoRedoManager || !imageGuid.isValid()) {
        return false;
    }

    QString guid = imageGuid.toString();

    // 获取当前的转换信息用于撤销操作
    double oldLengthRatio = m_imageCacheManager->getLengthRatio(guid);
    double oldTimeRatio = m_imageCacheManager->getTimeRatio(guid);
    double oldWavelengthRatio = m_imageCacheManager->getWavelengthRatio(guid);
    QString oldLengthUnit = m_imageCacheManager->getLengthUnit(guid);
    QString oldTimeUnit = m_imageCacheManager->getTimeUnit(guid);
    QString oldWavelengthUnit = m_imageCacheManager->getWavelengthUnit(guid);
    int oldXAxisUnit = m_imageCacheManager->getXAxisUnit(guid);
    int oldYAxisUnit = m_imageCacheManager->getYAxisUnit(guid);

    // 保存转换比例
    double lengthRatioValue = lengthRatio.toDouble();
    double timeRatioValue = timeRatio.toDouble();
    double wavelengthRatioValue = wavelengthRatio.toDouble();

    // 保存单位信息
    QString lengthUnitString = lengthUnit.toString();
    QString timeUnitString = timeUnit.toString();
    QString wavelengthUnitString = wavelengthUnit.toString();
    int xAxisUnitValue = xAxisUnit.toInt();
    int yAxisUnitValue = yAxisUnit.toInt();

    // 创建撤销函数
    auto undoFunc = [this, guid, oldLengthRatio, oldTimeRatio, oldWavelengthRatio, oldLengthUnit, oldTimeUnit, oldWavelengthUnit, oldXAxisUnit, oldYAxisUnit](const QVariant&) {
        if (m_imageCacheManager->containsImage(guid)) {
            m_imageCacheManager->setLengthRatio(guid, oldLengthRatio);
            m_imageCacheManager->setTimeRatio(guid, oldTimeRatio);
            m_imageCacheManager->setWavelengthRatio(guid, oldWavelengthRatio);
            m_imageCacheManager->setLengthUnit(guid, oldLengthUnit);
            m_imageCacheManager->setTimeUnit(guid, oldTimeUnit);
            m_imageCacheManager->setWavelengthUnit(guid, oldWavelengthUnit);
            m_imageCacheManager->setXAxisUnit(guid, oldXAxisUnit);
            m_imageCacheManager->setYAxisUnit(guid, oldYAxisUnit);
            return true;
        }
        return false;
    };

    // 创建重做函数
    auto redoFunc = [this, guid, lengthRatioValue, timeRatioValue, wavelengthRatioValue, lengthUnitString, timeUnitString, wavelengthUnitString, xAxisUnitValue, yAxisUnitValue](const QVariant&) {
        if (m_imageCacheManager->containsImage(guid)) {
            m_imageCacheManager->setLengthRatio(guid, lengthRatioValue);
            m_imageCacheManager->setTimeRatio(guid, timeRatioValue);
            m_imageCacheManager->setWavelengthRatio(guid, wavelengthRatioValue);
            m_imageCacheManager->setLengthUnit(guid, lengthUnitString);
            m_imageCacheManager->setTimeUnit(guid, timeUnitString);
            m_imageCacheManager->setWavelengthUnit(guid, wavelengthUnitString);
            m_imageCacheManager->setXAxisUnit(guid, xAxisUnitValue);
            m_imageCacheManager->setYAxisUnit(guid, yAxisUnitValue);
            return true;
        }
        return false;
    };

    // 创建操作信息结构体
    OperationInfo info;
    info.imageGuid = guid;
    info.type = ImageOperationType::AxisParamsChange;

    // 将修改前的值放入previousValue映射
    info.previousValue = QVariantMap({
        {"lengthRatio", oldLengthRatio},
        {"timeRatio", oldTimeRatio},
        {"wavelengthRatio", oldWavelengthRatio},
        {"lengthUnit", oldLengthUnit},
        {"timeUnit", oldTimeUnit},
        {"wavelengthUnit", oldWavelengthUnit},
        {"xAxisUnit", oldXAxisUnit},
        {"yAxisUnit", oldYAxisUnit}
    });

    // 将修改后的值放入newValue映射
    info.newValue = QVariantMap({
        {"lengthRatio", lengthRatioValue},
        {"timeRatio", timeRatioValue},
        {"wavelengthRatio", wavelengthRatioValue},
        {"lengthUnit", lengthUnitString},
        {"timeUnit", timeUnitString},
        {"wavelengthUnit", wavelengthUnitString},
        {"xAxisUnit", xAxisUnitValue},
        {"yAxisUnit", yAxisUnitValue}
    });

    info.undoFunc = undoFunc;
    info.redoFunc = redoFunc;
    info.description = tr("修改图像转换信息");

    // 添加到撤销/重做管理器
    m_undoRedoManager->addOperation(info);

    // 更新转换比例
    m_imageCacheManager->setLengthRatio(guid, lengthRatioValue);
    m_imageCacheManager->setTimeRatio(guid, timeRatioValue);
    m_imageCacheManager->setWavelengthRatio(guid, wavelengthRatioValue);

    // 更新单位信息
    m_imageCacheManager->setLengthUnit(guid, lengthUnitString);
    m_imageCacheManager->setTimeUnit(guid, timeUnitString);
    m_imageCacheManager->setWavelengthUnit(guid, wavelengthUnitString);
    m_imageCacheManager->setXAxisUnit(guid, xAxisUnitValue);
    m_imageCacheManager->setYAxisUnit(guid, yAxisUnitValue);

    return true;
}

QVariant ImageManagementPlugin::getImageConversionInfo(const QVariant &imageGuid) {
    if (!m_imageCacheManager || !imageGuid.isValid()) {
        return QVariantMap();
    }

    QString guid = imageGuid.toString();

    // 获取转换比例
    double lengthRatio = m_imageCacheManager->getLengthRatio(guid);
    double timeRatio = m_imageCacheManager->getTimeRatio(guid);
    double wavelengthRatio = m_imageCacheManager->getWavelengthRatio(guid);

    // 获取单位信息
    QString lengthUnit = m_imageCacheManager->getLengthUnit(guid);
    QString timeUnit = m_imageCacheManager->getTimeUnit(guid);
    QString wavelengthUnit = m_imageCacheManager->getWavelengthUnit(guid);
    int xAxisUnit = m_imageCacheManager->getXAxisUnit(guid);
    int yAxisUnit = m_imageCacheManager->getYAxisUnit(guid);

    // 创建返回的映射
    QVariantMap result;
    result["lengthRatio"] = lengthRatio;
    result["timeRatio"] = timeRatio;
    result["wavelengthRatio"] = wavelengthRatio;
    result["lengthUnit"] = lengthUnit;
    result["timeUnit"] = timeUnit;
    result["wavelengthUnit"] = wavelengthUnit;
    result["xAxisUnit"] = xAxisUnit;
    result["yAxisUnit"] = yAxisUnit;

    return result;
}

QVariant ImageManagementPlugin::setDefaultSavePath(const QVariant &path) {
    if (!m_imageCacheManager || !path.isValid()) {
        return false;
    }

    QString pathString = path.toString();
    if (pathString.isEmpty()) {
        return false;
    }

    // 直接调用ImageCacheManager设置默认保存路径
    m_imageCacheManager->setDefaultSavePath(pathString);
    return true;
}

QVariant ImageManagementPlugin::getDefaultSavePath() {
    if (!m_imageCacheManager) {
        return QString();
    }

    // 直接调用ImageCacheManager获取默认保存路径
    return m_imageCacheManager->getDefaultSavePath();
}

QVariant ImageManagementPlugin::setDefaultSaveFormat(const QVariant &format) {
    if (!m_imageCacheManager || !format.isValid()) {
        return false;
    }

    QString formatString = format.toString();
    if (formatString.isEmpty()) {
        return false;
    }

    // 直接调用ImageCacheManager设置默认保存格式
    m_imageCacheManager->setDefaultSaveFormat(formatString);
    return true;
}

QVariant ImageManagementPlugin::getDefaultSaveFormat() {
    if (!m_imageCacheManager) {
        return QString();
    }

    // 直接调用ImageCacheManager获取默认保存格式
    return m_imageCacheManager->getDefaultSaveFormat();
}

QVariant ImageManagementPlugin::updateOriginalImage(const QVariant &imageGuid, const QVariant &originalImage) {
    if (!m_imageCacheManager || !imageGuid.isValid()) {
        return false;
    }

    const QString guid = imageGuid.toString();

    if (originalImage.canConvert<QImage>()) {
        const QImage newImage = originalImage.value<QImage>();

        if (!m_imageCacheManager->containsImage(guid)) {
            m_imageCacheManager->setOriginalImage(guid, newImage, true);
        } else {
            m_imageCacheManager->setOriginalImage(guid, newImage, false);
        }

        updateImageDisplay(guid);
        return true;
    }

    return false;
}

QVariant ImageManagementPlugin::updateProcessedImage(const QVariant &imageGuid, const QVariant &processedImage, const QVariant &params)
{
    if (!m_imageCacheManager || !m_undoRedoManager || !imageGuid.isValid()) {
        return false;
    }

    QString guid = imageGuid.toString();

    // 检查图像是否在缓存中
    if (!m_imageCacheManager->containsImage(guid)) {
        return false;
    }

    // 检查是否为QImage类型
    if (processedImage.canConvert<QImage>()) {
        QImage newImage = processedImage.value<QImage>();

        // 获取当前的处理后图像用于撤销操作
        QImage oldImage = m_imageCacheManager->getProcessedImage(guid);

        // 创建撤销函数
        auto undoFunc = [this, guid, oldImage](const QVariant&) {
            if (m_imageCacheManager->containsImage(guid)) {
                m_imageCacheManager->setProcessedImage(guid, oldImage);
                updateImageDisplay(guid);
                return true;
            }
            return false;
        };

        // 创建重做函数
        auto redoFunc = [this, guid, newImage](const QVariant&) {
            if (m_imageCacheManager->containsImage(guid)) {
                m_imageCacheManager->setProcessedImage(guid, newImage);
                updateImageDisplay(guid);
                return true;
            }
            return false;
        };

        // 创建操作信息结构体
        OperationInfo info;
        info.imageGuid = guid;
        info.type = ImageOperationType::ImageProcessing;
        info.previousValue = QVariant::fromValue(oldImage);
        info.newValue = QVariant::fromValue(newImage);
        info.undoFunc = undoFunc;
        info.redoFunc = redoFunc;
        info.description = tr("修改处理后图像");

        // 添加到撤销管理器
        m_undoRedoManager->addOperation(info);

        // 更新处理后图像
        m_imageCacheManager->setProcessedImage(guid, newImage);

        // 更新显示界面
        updateImageDisplay(guid);
        addImageProcessingParam(imageGuid,params);
        return true;
    }

    return false;
}

QVariant ImageManagementPlugin::getOriginalImage(const QVariant &imageGuid) {
    if (!m_imageCacheManager) {
        return QVariant();
    }

    QString guid;

    // 如果提供了有效的imageGuid，则使用它
    if (imageGuid.isValid()) {
        guid = imageGuid.toString();
    } else {
        // 否则，获取当前选中图像的GUID
        QVariant selectedGuid = getCurrentSelectedImageGuid();
        if (selectedGuid.isValid()) {
            guid = selectedGuid.toString();
        } else {
            // 如果没有选中的图像，返回空的QVariant
            return QVariant();
        }
    }

    // 获取原始图像
    QImage originalImage = m_imageCacheManager->getOriginalImage(guid);

    if (!originalImage.isNull()) {
        return QVariant::fromValue(originalImage);
    }

    return QVariant();
}

QVariant ImageManagementPlugin::getProcessedImage(const QVariant &imageGuid) {
    if (!m_imageCacheManager) {
        return QVariant();
    }

    QString guid;

    // 如果提供了有效的imageGuid，则使用它
    if (imageGuid.isValid()) {
        guid = imageGuid.toString();
    } else {
        // 否则，获取当前选中图像的GUID
        QVariant selectedGuid = getCurrentSelectedImageGuid();
        if (selectedGuid.isValid()) {
            guid = selectedGuid.toString();
        } else {
            // 如果没有选中的图像，返回空的QVariant
            return QVariant();
        }
    }

    // 获取处理后图像
    QImage processedImage = m_imageCacheManager->getProcessedImage(guid);

    if (!processedImage.isNull()) {
        return QVariant::fromValue(processedImage);
    }

    return QVariant();
}

QVariant ImageManagementPlugin::getDisplayImage(const QVariant &imageGuid)
{
    // 根据是否有处理后的图像来决定发送哪个更新指令
    if (m_imageCacheManager && m_imageCacheManager->containsImage(imageGuid.toString())) {
        QImage processedImage = m_imageCacheManager->getProcessedImage(imageGuid.toString());
        if (!processedImage.isNull()) {
            return processedImage;
        } else {
            return m_imageCacheManager->getOriginalImage(imageGuid.toString());
        }
    }
    return QImage();
}


QVariant ImageManagementPlugin::undo(const QVariant &imageGuid) {
    if (!m_undoRedoManager || !imageGuid.isValid()) {
        return false;
    }

    QString guid = imageGuid.toString();

    // 获取操作类型和描述
    ImageOperationType operationType = ImageOperationType::Other;
    QString operationDescription;
    bool success = m_undoRedoManager->undo(guid, &operationType, &operationDescription);

    // 如果撤销成功，根据操作类型通知不同的插件
    if (success) {
        QString targetPluginName = "";
        QString message = QString(CMD_OPERATION_UNDO_SUCCESS ":%1:%2:%3").arg(guid).arg(operationTypeToString(operationType)).arg(operationDescription);

        // 根据操作类型选择目标插件
        switch (operationType) {
        case ImageOperationType::ImageProcessing:
            targetPluginName = IMAGE_PROCESSING_ALGORITHM_MANAGER_PLUGIN_NAME;
            break;
        case ImageOperationType::ImageMeasurement:
            targetPluginName = MEASUREMENT_MANAGEMENT_PLUGIN_NAME;
            break;
        case ImageOperationType::AxisParamsChange:
        case ImageOperationType::ImageCalibration:
        case ImageOperationType::ImageZoom:
            targetPluginName = GRAPHICS_DISPLAY_PLUGIN_NAME;
            break;
        case ImageOperationType::Other:
        default:
            // 其他操作不限制发送目标（发送给所有插件）
            targetPluginName = "";
            break;
        }

        emit pluginMessageSent(IMAGE_MANAGEMENT_PLUGIN_NAME, message, targetPluginName);
    }

    return success;
}

QVariant ImageManagementPlugin::redo(const QVariant &imageGuid) {
    if (!m_undoRedoManager || !imageGuid.isValid()) {
        return false;
    }

    QString guid = imageGuid.toString();

    // 获取操作类型和描述
    ImageOperationType operationType = ImageOperationType::Other;
    QString operationDescription;
    bool success = m_undoRedoManager->redo(guid, &operationType, &operationDescription);

    // 如果重做成功，根据操作类型通知不同的插件
    if (success) {
        QString targetPluginName = "";
        QString message = QString(CMD_OPERATION_REDO_SUCCESS ":%1:%2:%3").arg(guid).arg(operationTypeToString(operationType)).arg(operationDescription);

        // 根据操作类型选择目标插件
        switch (operationType) {
        case ImageOperationType::ImageProcessing:
            targetPluginName = IMAGE_PROCESSING_ALGORITHM_MANAGER_PLUGIN_NAME;
            break;
        case ImageOperationType::ImageMeasurement:
            targetPluginName = MEASUREMENT_MANAGEMENT_PLUGIN_NAME;
            break;
        case ImageOperationType::AxisParamsChange:
        case ImageOperationType::ImageCalibration:
        case ImageOperationType::ImageZoom:
            targetPluginName = GRAPHICS_DISPLAY_PLUGIN_NAME;
            break;
        case ImageOperationType::Other:
        default:
            // 其他操作不限制发送目标（发送给所有插件）
            targetPluginName = "";
            break;
        }

        emit pluginMessageSent(IMAGE_MANAGEMENT_PLUGIN_NAME, message, targetPluginName);
    }

    return success;
}

QVariant ImageManagementPlugin::canUndo(const QVariant &imageGuid) {
    if (!m_undoRedoManager || !imageGuid.isValid()) {
        return false;
    }

    QString guid = imageGuid.toString();
    return m_undoRedoManager->canUndo(guid);
}

QVariant ImageManagementPlugin::canRedo(const QVariant &imageGuid)
{
    if (!m_undoRedoManager || !imageGuid.isValid()) {
        return false;
    }

    QString guid = imageGuid.toString();
    return m_undoRedoManager->canRedo(guid);
}

QVariant ImageManagementPlugin::getCurrentOperationValue(const QVariant &imageGuid)
{
    if (!m_undoRedoManager || !imageGuid.isValid()) {
        return QVariant();
    }

    QString guid = imageGuid.toString();
    return m_undoRedoManager->getCurrentOperationValue(guid);
}

QVariant ImageManagementPlugin::addImageProcessingParam(const QVariant &imageGuid, const QVariant &params) {
    if (!m_imageCacheManager || !m_undoRedoManager || !imageGuid.isValid() || !params.isValid()) {
        return QVariant(-1);
    }

    QString guid = imageGuid.toString();

    // 检查图像是否在缓存中
    if (!m_imageCacheManager->containsImage(guid)) {
        return QVariant(-1);
    }

    // 检查参数是否为QVariantMap类型
    if (!params.canConvert<QVariantMap>()) {
        qWarning() << "参数必须为QVariantMap类型";
        return QVariant(-1);
    }

    QVariantMap paramMap = params.value<QVariantMap>();

    // 检查参数是否包含algorithmName
    if (!paramMap.contains("algorithmName")) {
        qWarning() << "处理参数必须包含algorithmName字段";
        return QVariant(-1);
    }

    // 获取当前所有参数用于撤销操作
    QList<QVariantMap> oldParamsList = m_imageCacheManager->getAllProcessingParams(guid);

    // 创建操作信息结构体
    OperationInfo info;
    info.imageGuid = guid;
    info.type = ImageOperationType::ImageProcessing;
    info.previousValue = QVariant::fromValue(oldParamsList);
    info.newValue = QVariant::fromValue(paramMap);
    info.description = tr("添加处理参数 - %1").arg(paramMap["algorithmName"].toString());

    // 创建撤销函数
    auto undoFunc = [this, guid](const QVariant& value) {
        if (m_imageCacheManager->containsImage(guid)) {
            QList<QVariantMap> oldParams = value.value<QList<QVariantMap>>();

            // 清除当前参数并恢复到之前的状态
            m_imageCacheManager->clearProcessingParams(guid, false);
            for (const QVariantMap& param : qAsConst(oldParams)) {
                m_imageCacheManager->addProcessingParam(guid, param, false);
            }
            return true;
        }
        return false;
    };

    // 创建重做函数
    auto redoFunc = [this, guid, paramMap](const QVariant&) {
        if (m_imageCacheManager->containsImage(guid)) {
            m_imageCacheManager->addProcessingParam(guid, paramMap, false);
            return true;
        }
        return false;
    };

    info.undoFunc = undoFunc;
    info.redoFunc = redoFunc;

    // 添加到撤销/重做管理器
    m_undoRedoManager->addOperation(info);

    // 添加参数
    int index = m_imageCacheManager->addProcessingParam(guid, paramMap, false);

    return QVariant(index);
}

QVariant ImageManagementPlugin::removeImageProcessingParam(const QVariant &imageGuid, const QVariant &index) {
    if (!m_imageCacheManager || !m_undoRedoManager || !imageGuid.isValid() || !index.isValid()) {
        return false;
    }

    QString guid = imageGuid.toString();
    int paramIndex = index.toInt();

    // 检查图像是否在缓存中
    if (!m_imageCacheManager->containsImage(guid)) {
        return false;
    }

    // 检查索引是否有效
    QList<QVariantMap> allParams = m_imageCacheManager->getAllProcessingParams(guid);
    if (paramIndex < 0 || paramIndex >= allParams.size()) {
        qWarning() << "参数索引无效";
        return false;
    }

    // 保存要移除的参数用于撤销操作
    QVariantMap paramToRemove = allParams[paramIndex];
    QString algorithmName = paramToRemove.value("algorithmName").toString();

    // 创建操作信息结构体
    OperationInfo info;
    info.imageGuid = guid;
    info.type = ImageOperationType::ImageProcessing;
    info.previousValue = QVariant::fromValue(paramToRemove);
    info.newValue = QVariant(paramIndex);
    info.description = tr("移除处理参数 - %1").arg(algorithmName);

    // 创建撤销函数
    auto undoFunc = [this, guid, paramIndex, paramToRemove](const QVariant&) {
        if (m_imageCacheManager->containsImage(guid)) {
            // 在原位置插入被移除的参数
            QList<QVariantMap> allParams = m_imageCacheManager->getAllProcessingParams(guid);

            // 清除当前参数并重建列表，在正确位置插入参数
            m_imageCacheManager->clearProcessingParams(guid, false);

            for (int i = 0; i < allParams.size(); ++i) {
                if (i == paramIndex) {
                    m_imageCacheManager->addProcessingParam(guid, paramToRemove, false);
                }
                if (i < allParams.size()) {
                    m_imageCacheManager->addProcessingParam(guid, allParams[i], false);
                }
            }

            // 如果原索引是最后一个，则直接添加到末尾
            if (paramIndex >= allParams.size()) {
                m_imageCacheManager->addProcessingParam(guid, paramToRemove, false);
            }

            return true;
        }
        return false;
    };

    // 创建重做函数
    auto redoFunc = [this, guid, paramIndex](const QVariant&) {
        if (m_imageCacheManager->containsImage(guid)) {
            m_imageCacheManager->removeProcessingParam(guid, paramIndex, false);
            return true;
        }
        return false;
    };

    info.undoFunc = undoFunc;
    info.redoFunc = redoFunc;

    // 添加到撤销/重做管理器
    m_undoRedoManager->addOperation(info);

    // 移除参数
    bool success = m_imageCacheManager->removeProcessingParam(guid, paramIndex, false);

    return success;
}

QVariant ImageManagementPlugin::clearImageProcessingParams(const QVariant &imageGuid) {
    if (!m_imageCacheManager || !m_undoRedoManager || !imageGuid.isValid()) {
        return false;
    }

    QString guid = imageGuid.toString();

    // 检查图像是否在缓存中
    if (!m_imageCacheManager->containsImage(guid)) {
        return false;
    }

    // 保存当前所有参数用于撤销操作
    QList<QVariantMap> oldParamsList = m_imageCacheManager->getAllProcessingParams(guid);

    // 创建操作信息结构体
    OperationInfo info;
    info.imageGuid = guid;
    info.type = ImageOperationType::ImageProcessing;
    info.previousValue = QVariant::fromValue(oldParamsList);
    info.newValue = QVariantList();
    info.description = tr("清除所有处理参数");

    // 创建撤销函数
    auto undoFunc = [this, guid](const QVariant& value) {
        if (m_imageCacheManager->containsImage(guid)) {
            QList<QVariantMap> oldParams = value.value<QList<QVariantMap>>();

            // 清除当前参数并恢复到之前的状态
            m_imageCacheManager->clearProcessingParams(guid, false);
            for (const QVariantMap& param : qAsConst(oldParams)) {
                m_imageCacheManager->addProcessingParam(guid, param, false);
            }
            return true;
        }
        return false;
    };

    // 创建重做函数
    auto redoFunc = [this, guid](const QVariant&) {
        if (m_imageCacheManager->containsImage(guid)) {
            m_imageCacheManager->clearProcessingParams(guid, false);
            return true;
        }
        return false;
    };

    info.undoFunc = undoFunc;
    info.redoFunc = redoFunc;

    // 添加到撤销/重做管理器
    m_undoRedoManager->addOperation(info);

    // 清除参数
    m_imageCacheManager->clearProcessingParams(guid, false);

    return true;
}

QVariant ImageManagementPlugin::getAllImageProcessingParams(const QVariant &imageGuid) {
    if (!m_imageCacheManager || !imageGuid.isValid()) {
        return QVariantList();
    }

    QString guid = imageGuid.toString();

    // 检查图像是否在缓存中
    if (!m_imageCacheManager->containsImage(guid)) {
        return QVariantList();
    }

    // 获取所有处理参数
    QList<QVariantMap> paramsList = m_imageCacheManager->getAllProcessingParams(guid);

    // 转换为QVariantList返回
    QVariantList resultList;
    for (const QVariantMap& param : qAsConst(paramsList)) {
        resultList.append(QVariant::fromValue(param));
    }

    return resultList;
}

QVariant ImageManagementPlugin::isImageProcessedByAlgorithm(const QVariant &imageGuid, const QVariant &algorithmName) {
    if (!m_imageCacheManager || !imageGuid.isValid() || !algorithmName.isValid()) {
        return false;
    }

    QString guid = imageGuid.toString();
    QString algoName = algorithmName.toString();

    // 检查图像是否在缓存中
    if (!m_imageCacheManager->containsImage(guid)) {
        return false;
    }

    // 获取该图像的所有处理参数
    QList<QVariantMap> paramsList = m_imageCacheManager->getAllProcessingParams(guid);

    // 遍历处理参数，检查是否有与指定算法名称匹配的参数
    for (const QVariantMap& param : qAsConst(paramsList)) {
        if (param.contains("algorithmName") && param["algorithmName"].toString() == algoName) {
            // 找到匹配的算法处理参数
            return true;
        }
    }

    // 没有找到匹配的算法处理参数
    return false;
}


QVariant ImageManagementPlugin::getImageProcessingParam(const QVariant &imageGuid, const QVariant &index) {
    if (!m_imageCacheManager || !imageGuid.isValid() || !index.isValid()) {
        return QVariantMap();
    }

    QString guid = imageGuid.toString();
    int paramIndex = index.toInt();

    // 检查图像是否在缓存中
    if (!m_imageCacheManager->containsImage(guid)) {
        return QVariantMap();
    }

    // 获取指定索引的处理参数
    QVariantMap param = m_imageCacheManager->getProcessingParam(guid, paramIndex);

    return QVariant::fromValue(param);
}

void handleCapturedImage(QObject* ctx, const QString& imageGuid, const QImage& image, int triggerMode)
{
    ImageManagementPlugin* self = qobject_cast<ImageManagementPlugin*>(ctx);
    if (!self) {
        return;
    }
    if (!self->m_imageCacheManager) {
        return;
    }
    if (triggerMode == 0)
    {
        self->m_imageCacheManager->setOriginalImage(imageGuid,image);
        emit self->updateCameraImage(image);
    }
    else
    {
        QString newGuid = self->m_imageCacheManager->addImageToCache(image);
        self->onSwitchToGraphicsDisplayWidget(newGuid);
        emit self->pluginMessageSent(IMAGE_MANAGEMENT_PLUGIN_NAME, QString("%1:%2").arg(CMD_IMAGE_COMPLETE).arg(imageGuid), DEVICE_MANAGEMENT_PLUGIN_NAME);
        //预处理图形

        QVariantMap parameters= self->m_ImagePreprocessingSettings->collectParameters();
        // 检查图像是否存在
        if (!(self->m_imageCacheManager && self->m_imageCacheManager->containsImage(imageGuid)))
        {
            return;
        }
        QString algorithmName;
        //预处理裁剪
        if(parameters[PARAM_ENABLE_CROP].toBool())
        {
            algorithmName= "图像裁剪";
            // 只发送消息给图像处理算法管理插件，让它主动来调用图像管理插件的接口
            emit self->pluginMessageSent(IMAGE_MANAGEMENT_PLUGIN_NAME,
                                         QString(CMD_IMAGE_READY_FOR_PROCESSING ":%1:%2:%3,%4,%5,%6")
                                         .arg(imageGuid,algorithmName,parameters[PARAM_TOP_LEFT].toString(),
                                              parameters[PARAM_TOP_RIGHT].toString(),
                                              parameters[PARAM_BOTTOM_LEFT].toString(),
                                              parameters[PARAM_BOTTOM_RIGHT].toString()),
                                         IMAGE_PROCESSING_ALGORITHM_MANAGER_PLUGIN_NAME);
        }
        //预处理旋转
        if(parameters[PARAM_ROTATION_ANGLE].toUInt()!=0)
        {
            algorithmName= "图像镜像";
            // 只发送消息给图像处理算法管理插件，让它主动来调用图像管理插件的接口
            emit self->pluginMessageSent(IMAGE_MANAGEMENT_PLUGIN_NAME,
                                         QString(CMD_IMAGE_READY_FOR_PROCESSING ":%1:%2:%3")
                                         .arg(imageGuid,algorithmName,parameters[PARAM_ROTATION_ANGLE].toString()),
                                         IMAGE_PROCESSING_ALGORITHM_MANAGER_PLUGIN_NAME);
        }
        //预处理镜像
        if(parameters[PARAM_MIRROR_TYPE].toUInt()!=0)
        {
            algorithmName= "图像旋转";
            // 只发送消息给图像处理算法管理插件，让它主动来调用图像管理插件的接口
            emit self->pluginMessageSent(IMAGE_MANAGEMENT_PLUGIN_NAME,
                                         QString(CMD_IMAGE_READY_FOR_PROCESSING ":%1:%2:%3")
                                         .arg(imageGuid,algorithmName,parameters[PARAM_MIRROR_TYPE].toString()),
                                         IMAGE_PROCESSING_ALGORITHM_MANAGER_PLUGIN_NAME);
        }
    }
}
